package com.atguigu.guli.serviceucenter.controller;

import com.atguigu.commonutils.utils.JwtUtil;
import com.atguigu.guli.serviceucenter.entity.Member;
import com.atguigu.guli.serviceucenter.entity.vo.LoginVo;
import com.atguigu.guli.serviceucenter.entity.vo.RegisterVo;
import com.atguigu.guli.serviceucenter.service.MemberService;
import com.atguigu.servicebase.exception.Assert;
import com.atguigu.servicebase.result.R;
import com.atguigu.servicebase.result.ResponseEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Api(tags = "前台用户登录")
@RestController
@RequestMapping("/ucenter/member")
@CrossOrigin
public class MemberApiController {

    @Autowired
    private MemberService memberService;

    @ApiOperation(value = "会员登录")
    @PostMapping("login")
    public R login(@RequestBody LoginVo loginVo) {
        String token = memberService.login(loginVo);
        return R.ok().data("token", token);
    }

    @ApiOperation(value = "会员注册")
    @PostMapping("register")
    public R register(@RequestBody RegisterVo registerVo){
        memberService.register(registerVo);
        return R.ok();
    }

    @ApiOperation(value = "根据token获取登录信息")
    @GetMapping("auth/getLoginInfo")
    public R getLoginInfo(HttpServletRequest request){
        try {
            String memberId = JwtUtil.getMemberIdByJwtToken(request);
            Assert.notEmpty(memberId, ResponseEnum.LAND_EXPIRATION);

            Member member = memberService.getById(memberId);
            return R.ok().data("item", member);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
